<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <el-row :gutter="20">
                <el-col :span="7">
                    <!-- clearable 启用清除图标   clear 清除事件   keyup.enter.native 回车事件 -->
                    <el-input
                        v-model="queryInfo.query"
                        placeholder="请输入内容"
                        class="input-with-select"
                        clearable
                        @clear="getUserList"
                        @keyup.enter.native="getUserSearch"
                    >
                        <el-button slot="append" icon="el-icon-search" @click="getUserSearch"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="openDialog">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 列表 -->
            <el-table :data="userlist" border stripe style="width: 100%">
                <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
                <el-table-column prop="username" label="用户名"></el-table-column>
                <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
                <el-table-column prop="mobile" label="手机号" width="180"></el-table-column>
                <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
                <el-table-column prop="mg_state" label="状态" width="180">
                    <template v-slot="scope">
                        <el-switch
                            v-model="scope.row.mg_state"
                            @change="userStateChange(scope.row)"
                        ></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template v-slot="scope">
                        <el-button
                            type="primary"
                            icon="el-icon-edit"
                            size="mini"
                            @click="openDialog(scope.row.id)"
                        ></el-button>
                        <el-button
                            type="danger"
                            icon="el-icon-delete"
                            size="mini"
                            @click="deleteUser(scope.row.id)"
                        ></el-button>
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
                            <el-button
                                type="warning"
                                icon="el-icon-setting"
                                size="mini"
                                @click="openDialogRole(scope.row)"
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="pageSizes"
                :page-size="queryInfo.pagesize"
                :layout="pageLayout"
                :total="total"
                background
            ></el-pagination>
        </el-card>
        <!-- 用户添加窗口 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogVisible"
            width="50%"
            @close="dialogClose"
        >
            <el-form
                :model="addForm"
                :rules="addForm.id === 0 ? addFormRules : editFormRules"
                ref="addFormRef"
                label-width="80px"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input
                        v-model="addForm.username"
                        maxlength="10"
                        :disabled="addForm.id === 0 ? false : true"
                    ></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" v-show="addForm.id === 0">
                    <el-input v-model="addForm.password" maxlength="20"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="mobile">
                    <el-input v-model="addForm.mobile" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email" maxlength="30"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配用户角色窗口 -->
        <el-dialog
            title="分配角色"
            :visible.sync="setRoleDialogVisible"
            width="50%"
            @close="closeRoleDialog"
        >
            <div>
                <p>用户名：{{ userInfo.username }}</p>
                <p>用户名：{{ userInfo.role_name }}</p>
                <p>
                    分配角色：
                    <el-select v-model="selectRoleId" placeholder="请选择">
                        <el-option
                            v-for="item in rolesList"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveUserRole">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import config from '@/util/config'
export default {
    data() {
        // 验证手机号码
        let checkPhone = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请输入手机号码'))
            } else {
                const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/
                if (reg.test(value)) {
                    callback()
                } else {
                    return callback(new Error('请输入正确的手机号'))
                }
            }
        }
        // 验证邮箱
        let checkEmail = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请输入邮箱'))
            } else {
                const reg = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
                if (reg.test(value)) {
                    callback()
                } else {
                    callback(new Error('请输入正确邮箱'))
                }
            }
        }
        return {
            queryInfo: {
                query: '',
                pagenum: config.pageNum,
                pagesize: config.pageSize,
            },
            pageSizes: config.pageSizes,
            pageLayout: config.pageLayout,
            userlist: [],
            total: 0,
            dialogVisible: false,
            dialogTitle: '',
            // 表单数据
            addForm: {
                id: 0,
                username: '',
                password: '',
                mobile: '',
                email: ''
            },
            // 表单验证规则
            addFormRules: {
                username: [
                    { required: true, message: '请输入用戶名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ],
                mobile: [
                    { required: true, validator: checkPhone, trigger: 'blur' }
                ],
                email: [
                    { required: true, validator: checkEmail, trigger: 'blur' }
                ]
            },
            editFormRules: {
                username: [
                    { required: true, message: '请输入用戶名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                mobile: [
                    { required: true, validator: checkPhone, trigger: 'blur' }
                ],
                email: [
                    { required: true, validator: checkEmail, trigger: 'blur' }
                ]
            },
            setRoleDialogVisible: false,
            userInfo: {},
            rolesList: [],
            selectRoleId: ''
        }
    },
    created() {
        this.getUserList()
    },
    methods: {
        // 列表数据
        async getUserList() {
            const { data: res } = await this.$http.get('users', {
                params: this.queryInfo
            })
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.userlist = res.data.users
            this.total = res.data.total
        },
        // 搜索
        getUserSearch() {
            this.queryInfo.pagenum = 1
            this.getUserList()
        },
        // 监听 pagesize 改变
        handleSizeChange(newSize) {
            this.queryInfo.pagesize = newSize
            this.getUserList()
        },
        // 监听 pagenum 改变
        handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },
        // 监听 switch 用户状态
        async userStateChange(userInfo) {
            const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
            if (res.meta.status !== 200) {
                this.mg_state = !this.mg_state
                this.$message.error(res.meta.msg)
            }
            this.$message.success(res.meta.msg)
        },
        // 监听添加用户窗口关闭，并重置表单
        dialogClose() {
            this.$refs.addFormRef.resetFields()
        },
        // 打开添加/编辑用户窗口
        async openDialog(id) {
            this.dialogVisible = true
            if (id > 0) {
                this.dialogTitle = '编辑用户'
                const { data: res } = await this.$http.get('users/' + id)
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                this.addForm = res.data
            } else {
                this.dialogTitle = '添加用户'
            }
        },
        // 保存用户信息
        saveUser() {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return
                // 编辑用户信息
                if (this.addForm.id > 0) {
                    const { data: res } = await this.$http.put('users/' + this.addForm.id, this.addForm)
                    if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                    this.$message.success(res.meta.msg)
                } else {    // 添加用户信息
                    const { data: res } = await this.$http.post('users', this.addForm)
                    if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
                    this.$message.success(res.meta.msg)
                }
                this.dialogVisible = false
                // 重新获取列表数据
                this.getUserList()
            })
        },
        // 删除用户
        async deleteUser(id) {
            const confirmRes = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                type: 'warning'
            }).catch(err => err)
            if (confirmRes !== 'confirm') return this.$message.info('已取消删除')
            const { data: res } = await this.$http.delete('users/' + id)
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success(res.meta.msg)
            this.getUserList()
        },
        // 打开分配角色窗口
        async openDialogRole(userInfo) {
            this.userInfo = userInfo
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.rolesList = res.data
            this.setRoleDialogVisible = true
        },
        // 保存分配角色
        async saveUserRole() {
            if (!this.selectRoleId) return this.$message.error('请选择分配的角色!')
            const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
                rid: this.selectRoleId
            })
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success(res.meta.msg)
            this.getUserList()
            this.setRoleDialogVisible = false
        },
        closeRoleDialog() {
            this.rolesList = []
            this.selectRoleId = ''
        }
    },
}
</script>

<style lang="less" scoped>
</style>